package leetcode.d_1_99;

// https://leetcode.cn/problems/longest-common-prefix/description/
// 最长公共前缀
public class P14 {
    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        String comm = strs[0];
        for (int i=1; i<strs.length; i++) {
            comm = getCommStr(comm, strs[i]);
            if (comm.length() == 0) {
                break;
            }
        }
        return comm;
    }

    public String getCommStr(String s1, String s2) {
        int len = Math.min(s1.length(), s2.length());
        int idx = 0;
        while((idx < len) && (s1.charAt(idx) == s2.charAt(idx))) {
            idx++;
        }
        return s1.substring(0, idx);
    }

    public static void main(String[] args) {
        P14 test = new P14();
        System.out.println(test.longestCommonPrefix(new String[]{"flower", "flow", "flight"})); // fl
    }
}
